from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from django.contrib.auth.hashers import make_password, check_password
from django.core.urlresolvers import reverse
from myadmin import models


# Create your views here.

# 前台注册界面
def register(request): 
    if request.method == 'GET':  
        return render(request,'myhome/register.html')
    elif request.method == 'POST':
        try:
            # 验证手机的验证码是否正确
            # if request.POST['phone'] != request.session['msgcode']['phone'] or request.POST['code'] != request.session['msgcode']['code']:
            #     return HttpResponse('<script>alert("注册失败,验证码不正确");location.href="'+reverse('myhome_register')+'"</script>')

            pwd = request.POST['password']
            username = request.POST['username']
            if len(pwd) < 8 or len(username) == 0 :
                return HttpResponse('<script>alert("注册失败，请重新注册！");location.href="'+reverse('myhome_register')+'"</script>')
            else:
                # 密码加密
                password  = make_password(pwd, None, 'pbkdf2_sha256')
                tel = request.POST['phone']
                data = {'username':username,'password':password,'tel':tel,'pic_url':''}

                # 执行注册
                db = models.Users(**data)
                db.save()
                # 跳转登录页面
                return HttpResponse('<script>alert("注册成功，请登录！");location.href="'+reverse('myhome_login')+'"</script>')
        
        except:
            return HttpResponse('<script>alert("注册失败，请重新注册！");location.href="'+reverse('myhome_register')+'"</script>')

# 验证手机号
def checkPhone(request):
    # 接受手机号
    tel = request.GET.get('phone')
    # 到数据库查询
    num = models.Users.objects.filter(tel = tel).count()
    
    if num :
        return JsonResponse({'error':1,'msg':'手机号已被注册！'})
    else:
        return JsonResponse({'error':0,'msg':'手机号未注册！'})

# 发送验证码到注册的手机号上
def sendmsg(request):
    #接口类型：互亿无线触发短信接口，支持发送验证码短信、订单通知短信等。
    #账户注册：请通过该地址开通账户http://user.ihuyi.com/register.html
    #注意事项：
    #（1）调试期间，请用默认的模板进行测试，默认模板详见接口文档；
    #（2）请使用 用户名 及 APIkey来调用接口，APIkey在会员中心可以获取；
    #（3）该代码仅供接入互亿无线短信接口参考使用，客户可根据实际需要自行编写；
      
    # import urllib2
    import urllib
    import urllib.request
    import json
    import random
    #用户名 查看用户名请登录用户中心->验证码、通知短信->帐户及签名设置->APIID
    account  = "C28614808" 
    #密码 查看密码请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
    password = "382cf05da19a5326088f51b6da0ddfa7"
    # 接受注册页面提供的手机号
    mobile = request.GET.get('phone')
    # 随机验证码
    code = str(random.randint(10000,99999))
    # 把验证码存入session
    request.session['msgcode'] = {'phone':mobile,'code':code}
    # text = "您的验证码是："+code+"。请不要把验证码泄露给其他人。"
    # data = {'account': account, 'password' : password, 'content': text, 'mobile':mobile,'format':'json' }
    # req = urllib.request.urlopen(
    #     url= 'http://106.ihuyi.com/webservice/sms.php?method=Submit',
    #     data= urllib.parse.urlencode(data).encode('utf-8')
    # )
    # content =req.read()
    # res = json.loads(content.decode('utf-8'))
    # print(res)
    return HttpResponse('aa')

# 前台登录
def login(request):
    nextpath = request.GET.get('nextpath','/')
    args = eval(request.GET.get('args','{}'))
    a = ''
    for k,v in args.items():
        a+= '&'+k+'='+v
    nexturl = nextpath+'?'+a

    if request.method == 'GET':
        return render(request,'myhome/login.html')

    elif request.method == 'POST':
        try:
            # 先根据手机号获取用户
            db = models.Users.objects.get(tel=request.POST['phone'])
            # 在对比密码是否正确
            res = check_password(request.POST['password'],db.password)
            if res:
                # 用户名和密码都正确
                # 在session中存入登录凭证
                request.session['VipUser'] = {'username':db.username,'tel':db.tel,'id':db.id,'pic_url':db.pic_url}
                # 跳转到首页
                return HttpResponse('<script>alert("登录成功！");location.href="'+nexturl+'"</script>')
            else:
                # 密码错误
                pass
        except:
            # 手机号不存在
            pass
        return HttpResponse('<script>alert("登录失败！");location.href="'+reverse('myhome_login')+'"</script>')

# 退出登录
def logout(request):
    del request.session['VipUser']
    return HttpResponse('<script>alert("账号已退出！");location.href="'+reverse('myhome_index')+'"</script>')

# 前台首页
def index(request):
    # 获取所有的一级分类
    data = models.Cates.objects.filter(pid=0)

    # 获取当前一级类下的二级分类
    for i in data:
        i.sub = models.Cates.objects.filter(pid=i.id)

    context = {'data':data}

    return render(request,'myhome/index.html',context)

# 前台商品列表页
def goodslist(request):
    # 接受查询二级分类的id
    cid = request.GET.get('cid')
    # 获取所有的二级分类
    db = models.Cates.objects.get(id=cid)

    db.goodslist = models.Goods.objects.filter(cateid=db).order_by(request.GET.get('orderby','id'))

    context = {'data':db}
    
    return render(request,'myhome/list.html',context)

# 商品详情页
def goodsinfo(request):
    # 商品id
    gid = request.GET.get('gid')
    # 获取商品对象
    db = models.Goods.objects.get(id=gid)
    # 获取此商品的分类下的所有商品
    goodsdata = models.Goods.objects.filter(cateid=db.cateid)
    # 分配数据
    context = {'data':db,'goodsdata':goodsdata}
    
    return render(request,'myhome/info.html',context)

# 商品购物车
def cart(request):
    # 获取登录会员的id
    userid = request.session['VipUser']['id']
    # 获取当前会员添加到购物车的商品
    data = models.Cart.objects.filter(uid=userid)
    context = {'data':data}
    return render(request,'myhome/cart.html',context)

# 商品添加至购物车
def cartadd(request):
    # 获取会员id、商品id、商品数量
    user = models.Users.objects.get(id=request.session['VipUser']['id'])
    goods = models.Goods.objects.get(id = request.GET.get('gid'))
    num = int(request.GET.get('num'))

    # 检查当前的商品是否已经存在购物车
    res = models.Cart.objects.filter(goodsid=goods).filter(uid=user)

    if res.count():
        #已存在,更新数量
        for i in res:
            i.num += num
            i.save()
    else:
        # 添加至数据库
        db = models.Cart(uid=user,goodsid=goods,num=num)
        db.save()

    return JsonResponse({'error':0,'msg':'加入购物车成功！'})

# 购物车中商品的变更
def cartedit(request):
   # 购物车id  数量
    cartid = request.GET.get('cartid')
    num = request.GET.get('num')

    # 获取购物车对象
    ob = models.Cart.objects.get(id=cartid)
    ob.num = int(num)
    ob.save()

    # 运算小计价格
    totalprice = ob.num*ob.goodsid.price

    return JsonResponse({'error':0,'msg':'修改成功','totalprice':"{:.2f}".format(totalprice)})

# 删除购物车中的某个商品
def cartdel(request):
    gid = request.GET.get('cid')
    # 获取数据
    db = models.Cart.objects.get(id=gid)
    db.delete()

    return HttpResponse('<script>alert("删除成功！");location.href="'+reverse('myhome_cart')+'"</script>')

# 删除购物车中的所有商品
def cartAlldel(request):
    # 获取购物车中的所有商品
    data = models.Cart.objects.all()
    # 循环删除商品
    for i in data:
        i.delete()
    # 返回购物车
    return HttpResponse('<script>alert("删除成功！");location.href="'+reverse('myhome_cart')+'"</script>')

# 商品确定订单页面
def pay(request):
    # 接受订单商品的id
    cartids = eval(request.GET.get('cartids'))

    # 获取商品数据
    data = models.Cart.objects.filter(id__in=cartids)

    # 获取所有的一级城市数据
    province = models.Citys.objects.filter(level=1)

    # 分配数据
    context = {'data':data,'province':province}

    return render(request,'myhome/pay.html',context)

# 返回城市数据
def getcitys(request):
    # 根据id获取下一级的城市数据,返回json
    data = models.Citys.objects.filter(upid=request.GET.get('id')).values()
    # print(data)
    # 解析json数据
    return JsonResponse(list(data),safe=False)

# 添加收货地址
def addressadd(request):
    # 接收地址信息
    data = eval(request.GET.get('data'))
    # print(data)
    # 获取当前用户对象
    data['uid'] = models.Users.objects.get(id = request.session['VipUser']['id'])
    print(data)
    # 存储数据
    db = models.Address(**data)
    db.save()

    return JsonResponse({'1234':1})

# 读取所有收货地址
def addresslist(request):
    
    # 获取当前用户的所有收货地址
    data = models.Address.objects.filter(uid = request.session['VipUser']['id']).values()
    # print(data)
    # 遍历所有数据
    for i in data:
        i['province'] = models.Citys.objects.get(id=i['province']).name
        # print(i['province'])
        i['city'] = models.Citys.objects.get(id=i['city']).name
        i['county'] = models.Citys.objects.get(id=i['county']).name

    return JsonResponse({'error':0,'data':list(data)},safe=False)

# 修改默认地址
def addressedit(request):
    # print('aaaa')
    # 接受id
    editid = int(request.GET.get('id'))
    print(editid,type(editid))
    # 读取所有地址
    data = models.Address.objects.filter(uid = request.session['VipUser']['id'])
    print(data)
    for i in data:
        print(i.id,type(i.id)) 
        if i.id == editid:
            i.isCheck = 1
            i.save()
        else:
            i.isCheck = 0
            i.save()
    return JsonResponse({'error':0,'msg':'修改成功！'})

# 删除单击的收货地址
def addressdel(request):
    # 接受需要删除的收货地址id
    delid = int(request.GET.get('id'))
    print(delid,type(delid))
    # 获取地址对象
    data = models.Address.objects.get(id=delid)
    print(data)
    if data.isCheck == 0:
        data.delete()
        return JsonResponse({'error':0,'msg':'地址删除成功！'})
    if data.isCheck == 1:
        return JsonResponse({'error':1,'msg':'此地址为默认地址，不可删除！'})

# 商品支付成功页面
def ordercreate(request):

    # 获取提交的订单数据
    data = request.POST.dict()
    data.pop('csrfmiddlewaretoken')
    print(data)
    # {'cartids': '["9","10"]', 'addressid': '4', 'paytype': 'yinlian', 'wl': 'shentong'}
    # 添加订单
    # 获取用户对象
    user = models.Users.objects.get(id=request.session['VipUser']['id'])
    # 获取地址信息
    addr = models.Address.objects.get(id=data['addressid'])
    province = models.Citys.objects.get(id=addr.province).name
    city = models.Citys.objects.get(id=addr.city).name
    county = models.Citys.objects.get(id=addr.county).name
    receiveaddress = province+city+county+addr.info

    # 总价计算
    totalprice = 0
    cart = models.Cart.objects.filter(id__in=eval(data['cartids']))
    for x in cart:
        totalprice += x.num*x.goodsid.price
    
    # 准备订单数据
    orderdata={'uid':user,'receiver':addr.receiver,'receivephone':addr.receivephone,'receiveaddress':receiveaddress,'paytype':data['paytype'],'wl':data['wl']}
    orderdata['totalprice'] = totalprice
    
    # 创建订单
    order = models.Order(**orderdata)
    order.save()

    # 生成订单详情
    for x in cart:
        odinfo = models.OrderInfo()
        odinfo.orderid = order
        odinfo.goodsid = x.goodsid.id
        odinfo.title = x.goodsid.title
        odinfo.pic_url = x.goodsid.pic_url
        odinfo.price = x.goodsid.price
        odinfo.num = x.num
        # 添加到订单详情
        odinfo.save()
        # 删除购物车中已经下单的商品
        x.delete()

    # 跳转到支付页面
    return HttpResponse('<script>alert("订单创建成功，请前往支付！");location.href="'+reverse('myhome_orderbuy')+'?orderid='+str(order.id)+'"</script>')
    # return HttpResponse('订单支付页面!')

# 订单支付页面
def orderbuy(request):
    # 订单id
    orderid = int(request.GET['orderid'])
    # print(orderid,type(orderid))

    # 获取订单信息
    data = models.Order.objects.get(id=orderid)
    data.status = 1
    data.save()
    # 分配数据
    context = {'data':data}

    return render(request,'myhome/paysuccess.html',context)



# 个人中心
def person(request):
 
    return render(request,'myhome/person/personal.html')

# 个人信息
def personinfo(request):

    # 获取当前用户id
    uid = request.session['VipUser']['id']
    # 获取用户信息
    data = models.Users.objects.get(id=uid)
    # 分配数据
    context = {'data':data}

    return render(request,'myhome/person/personalinfo.html',context)


# 修改个人信息
def personinfoedit(request):

    # 获取当前用户id
    uid = request.session['VipUser']['id']
    # 获取用户信息
    data = models.Users.objects.get(id=uid)

    data.username = request.POST.get('username')

    data.sex = request.POST.get('sex')
    
    data.age = request.POST.get('age')
    if data.age == '':
        data.age = None
    
    data.tel = request.POST.get('tel')

    data.email = request.POST.get('email')

    data.save()

    return HttpResponse('<script>alert("更新成功");location.href="'+reverse('myhome_personinfo')+'"</script>')

# 个人收货地址
def personaddress(request):
    # 获取所有的一级城市数据
    province = models.Citys.objects.filter(level=1)

    context = {"province":province}
    
    return render(request,'myhome/person/personaladdress.html',context)

    return JsonResponse({'data':data,'p':p})

def editaddress(request):
    data = request.POST.dict()
    data.pop('csrfmiddlewaretoken')
    # print(data)
    olddata = models.Address.objects.get(id=int(data['id']))
    # print(olddata)
    olddata.receiver = data['receiver']
    olddata.receivephone = data['receivephone']
    olddata.province = data['province']
    olddata.city = data['city']
    olddata.county = data['county']
    olddata.info = data['info']
    olddata.save() 


    return render(request,'myhome/person/personaladdress.html')

# 修改个人收货地址
def personaddressedit(request):
    
    editid = int(request.GET['editid'])
    # 默认省份
    p = request.GET['p']
    # # 默认市
    c = request.GET['c']
    # # 默认区县
    d = request.GET['d']
    # print(p,c,d)
    # print(editid,type(editid))

    # 取出原地址的省市县的id
    pid = models.Citys.objects.get(name=p).id
    cid = models.Citys.objects.get(name=c).id
    did = models.Citys.objects.get(name=d).id
    # print('aaaaaaaaaaaaaaaaaaaa')
    print(pid,type(pid))
    # print(cid)
    # print(did)   
    # print('aaaaaaaaaaaaaaaaaaaa')

    data = models.Address.objects.get(id=editid)
    # print(data.province,type(data.province))

    # 获取所有的一级城市数据
    province = models.Citys.objects.filter(level=1)
    city = models.Citys.objects.filter(upid= pid)
    county = models.Citys.objects.filter(upid=cid)

    context = {'data':data,'province':province,'city':city,'county':county,'pid':pid,'cid':cid,'did':did,} 

    return render(request,'myhome/person/personaladdressedit.html',context)

# 个人订单管理
def personorder(request):
    # 获取当前用户id
    uid=request.session['VipUser']['id']
    # 获取当前用户的所有订单
    user = models.Users.objects.get(id=uid)
    # print(user)
    # 分配数据
    context = {'user':user}

    return render(request,'myhome/person/personalorder.html',context)